<template>
  <div class="mengli-income-item">
    <div class="title-container">
      <Title title="收入项">
        <div v-if="showCountFields && !showMobilePage" class="fields-count">
        <img :src="incomeAmountIcon" class="img" alt="">
        {{ countFieldName }}：<span class="text">{{ countField }}</span>
        </div>
      </Title>
      <PlainCreateBtn v-if="hasAddAuth" class="create-btn" size="small" @click="openDialog">添加收入项</PlainCreateBtn>
    </div>
    <div v-if="isDetail" :class="{'is-mobile': showMobilePage}" class="filter-wrap">
      <div v-if="showCountFields && showMobilePage" class="fields-count">
        <img :src="incomeAmountIcon" class="img" alt="">
        {{ countFieldName }}：<span class="text">{{ countField }}</span>
      </div>
      <FilterInput
        v-if="isDetail"
        ref="FilterToolRef"
        v-model="queryForm"
        :filter-list="filterList"
        :show-mobile-icon="showMobilePage"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"/>
    </div>
    <div v-loading="loading" class="income-item-table">
      <div v-if="value.length > 0">
        <el-table
          ref="allOrderTableRef"
          :data="handleData(value)"
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row>

          <el-table-column align="left" label="收入编号" width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.incomeItemNo" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="收入项" width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.incomeItemName"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="收入细项" width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.incomeDetail" />
            </template>
          </el-table-column>
          <el-table-column align="right" label="单价(元)" width="100" sortable prop="unitPrice">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.unitPrice" :price="scope.row.unitPrice" />
            </template>
          </el-table-column>
          <el-table-column :sort-method="sortMethod" align="left" label="数量" width="100" sortable prop="number">
            <template slot-scope="scope">
              <div v-if="scope.row.number || scope.row.number === 0">{{ scope.row.number | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="right" label="总价(元)" width="100" sortable prop="totalPrice">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.totalPrice" :price="scope.row.totalPrice" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="税率" width="100">
            <template slot-scope="scope">
              <ToolTip v-if="scope.row.taxRate || scope.row.taxRate === 0" :content="scope.row.taxRate + '%'" />
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="说明" width="100" >
            <template slot-scope="scope">
              <ToolTip :content="scope.row.explain"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="交付时间" width="120" sortable prop="deliverTime">
            <template slot-scope="scope">
              <div v-if="scope.row.deliverTime || scope.row.deliverTime === 0">{{ scope.row.deliverTime | format('YYYY/MM/DD') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="业绩月份" width="100" prop="month">
            <template slot-scope="scope">
              <div v-if="scope.row.month">{{ scope.row.month | format('YYYY/MM') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="款项应收时间" width="110" prop="receivableTime">
            <template slot-scope="scope">
              <div v-if="scope.row.receivableTime">{{ scope.row.receivableTime | format('YYYY/MM/DD') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="分期月份" width="170">
            <template slot-scope="scope">
              <div v-if="scope.row.incomeStartTime && scope.row.incomeEndTime">{{ scope.row.incomeStartTime | format('YYYY/MM') }} - {{ scope.row.incomeEndTime | format('YYYY/MM') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建人" width="100">
            <template slot-scope="scope">
              <CheckUserInfo :user-id="scope.row.creatorId" :label="scope.row.creator" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建时间" width="150" sortable prop="createTime">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime || scope.row.createTime === 0">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="审批状态" width="110">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus || scope.row.approvalStatus === 0">{{ scope.row.approvalStatus | approvalStatusFilter }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="审批时间" width="150" prop="approvalTime">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalTime || scope.row.approvalTime === 0">{{ scope.row.approvalTime | format('YYYY/MM/DD HH:mm') }}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" fixed="right" label="操作" width="110">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus !== 1 || !isDetail" class="flex">
                <div v-if="hasEditAuth" :class="{'br': (isDetail && hasRouteAuth('mengli:iPOrder:incomeApproval')) || hasDeleteAuth}" class="button-text" @click="openDialog(scope.row)">编辑</div>
                <MoreOpeator
                  v-if="(isDetail && hasRouteAuth('mengli:iPOrder:incomeApproval')) || hasDeleteAuth"
                  :list="[
                    {label: '审批', handelClick: () => {approval(scope.row)}, auth: isDetail && scope.row.approvalStatus === 0 && hasRouteAuth('mengli:iPOrder:incomeApproval')},
                    {label: '作废审批', handelClick: () => {approval(scope.row, true)}, auth: isDetail && scope.row.approvalStatus !== 0 && hasRouteAuth('mengli:iPOrder:incomeApproval')},
                    {label: '删除', handelClick: () => {toDelete(scope.row)}, auth: hasDeleteAuth},
                ]">
                  <div slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                </MoreOpeator>
              </div>
              <div v-else-if="isDetail && hasRouteAuth('mengli:iPOrder:incomeApproval')" class="button-text" @click="approval(scope.row, true)">作废审批</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="value.length > 10 || isDetail" style="margin-top:12px;display:flex;">
          <span v-if="!showMobilePage" style="flex:1"/>
          <el-pagination
            :page-sizes="[20, 50, 100, 250, 500]"
            :page-size="isDetail?incomeListData.perPage : pageSize"
            :current-page="isDetail?incomeListData.page : currentPage"
            :total="isDetail?incomeListData.total :value.length"
            :layout="showMobilePage?'total, prev, next, jumper':'total, sizes, prev, pager, next, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </div>
      <empty-placeholder v-else :empty-img="emptyImg" image-size="90px" style="margin-bottom: 24px" />
    </div>
    <createDialog ref="createDialog" :is-detail="isDetail" @addIcomeItem="addIcomeItem" @editIcomeItem="editIcomeItem" />
  </div>
</template>

<script>
// component
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import createDialog from './createDialog';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
// api
import { mapState } from 'vuex';
import { MessageBox } from 'element-ui';
import { approvelIncomeItem } from '@/api/mengliOrder';
// tool
import { format } from '@/filters/date';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import { moneyFilter } from '@/filters/number';
import emptyImg from '@/assets/empty-data-icon.png';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { generateUUID } from '@/utils/tools';

export default {
  components: { Title, EmptyPlaceholder, createDialog, MoreOpeator },
  filters: { moneyFilter, format,
    approvalStatusFilter(num) {
      const obj = { 0: '待审批', 1: '已通过', 2: '未过审' };
      return obj[num] || '--';
    }
  },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    hasAddAuth: {
      type: Boolean,
      default: false
    },
    hasEditAuth: {
      type: Boolean,
      default: false
    },
    hasDeleteAuth: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    showCountFields: {
      type: Boolean,
      default: false
    },
    fieldName: {
      type: String,
      default: 'totalPrice'
    },
    countFieldName: {
      type: String,
      default: '收入总额(元)'
    },
    incomeListData: {
      type: Object,
      default: () => {
        return {
          items: [],
          page: 1,
          perPage: 20,
          total: 0
        };
      }
    }
  },
  data() {
    return {
      emptyImg, incomeAmountIcon,
      loading: false,
      isEdit: false,
      currentPage: 1,
      pageSize: 10,
      queryForm: {}
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    // xx总额
    countField() {
      let res = '';
      if (this.isDetail && this.detailData) {
        // return moneyFilter(this.detailData.income / 100);
        const num = this.incomeListData.otherData ? this.incomeListData.otherData.totalIncome : null;
        if (!num && num !== 0) return '--';
        res = moneyFilter(num);
        return res + '元';
      }
      const list = this.value || [];
      if (!Array.isArray(list) || !list || !list.length) {
        // return Number(0).toFixed(2);
        res = Number(0).toFixed(2);
        return res + '元';
      }
      // return Number(list.map(el => Number(el[`${this.fieldName}`])).reduce((pre, next) => { return pre + next; }, 0)).toFixed(2);
      res = Number(list.map(el => Number(el[`${this.fieldName}`])).reduce((pre, next) => { return pre + next; }, 0)).toFixed(2);
      return res + '元';
    },
    filterList() {
      return [
        { keyword: 'incomeItemNo', labelWidth: '96px', name: '收入编号', type: 'input' },
        { keyword: 'incomeItemName', labelWidth: '96px', name: '收入项', type: 'input' },
        { keyword: 'incomeDetail', labelWidth: '96px', name: '收入细项', type: 'input' },
        { keyword: 'explain', labelWidth: '96px', name: '说明', type: 'input' },
        { keyword: 'creator', labelWidth: '96px', name: '创建人', type: 'input' },
        { keyword: 'approvalStatus', name: '审批状态', type: 'select', options: [
          { value: 0, label: '待审批' }, { value: 1, label: '已通过' }, { value: 2, label: '未过审' }
        ] },
        { keyword: 'deliverTime', labelWidth: '96px', name: '交付时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'month', format: 'yyyy/MM', labelWidth: '96px', name: '业绩月份', timeType: 'monthrange', type: 'rangeDate' },
        { keyword: 'receivableTime', labelWidth: '96px', name: '款项应收时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'incomeTime', format: 'yyyy/MM', labelWidth: '96px', name: '分期月份', timeType: 'monthrange', type: 'rangeDate' },
        { keyword: 'createTime', labelWidth: '96px', name: '创建时间', timeType: 'daterange', type: 'rangeDate' }
      ];
    }
  },
  methods: {
    hasRouteAuth,
    setParams(params) {
      this.queryForm = params;
      this.queryClick();
    },
    addIcomeItem(data) {
      if (!this.isDetail) data._id = generateUUID();
      if (this.isDetail) {
        const params = this.getParams();
        params.page = 1;
        this.$emit('addIcomeItem', data, params);
      } else {
        this.value.unshift(data);
        this.$emit('changeValue', this.value);
      }
    },
    editIcomeItem({ data }) {
      const index = this.value.findIndex(i => {
        if (data.id) {
          return i.id === data.id;
        }
        return i._id === data._id;
      });
      this.$set(this.value, index, data);
      this.$emit('changeValue', this.value);
      if (this.isDetail) {
        const params = this.getParams();
        params.page = this.incomeListData.page;
        this.$emit('editIcomeItem', data, params);
      }
    },
    openDialog(data = null) {
      if (data && ['IP衍生品', 'IP授权'].includes(data.incomeItemName) && data.id) {
        this.$refs.createDialog.getRelatedCost(data.id).then(() => {
          this.$refs.createDialog.openDialog(data);
        }).catch(err => console.error(err.message));
      } else {
        this.$refs.createDialog.openDialog(data);
      }
    },
    toDelete(item, index) {
      this.$confirm('是否确定删除该收入项', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        if (this.isDetail) {
          const params = this.getParams();
          params.page = 1;
          this.$emit('deleteIcomeItem', item, params);
          this.currentPage = 1;
        } else {
          this.value.splice(index, 1);
          this.currentPage = 1;
          // this.$message.success('删除成功');
          this.$emit('changeValue', this.value);
        }
      });
    },
    sortMethod(a, b) {
      return Number(a.number) - Number(b.number);
    },
    // 翻页
    handleData(tableData) {
      return this.isDetail ? tableData : tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      if (this.isDetail) {
        this.queryClick();
      }
    },
    handleCurrentChange(val) {
      if (this.isDetail) {
        const params = this.getParams();
        params.page = val;
        this.$emit('freshData', params);
      } else {
        this.currentPage = val;
      }
    },
    queryClick() {
      const params = this.getParams();
      params.page = 1;
      this.$emit('freshData', params);
    },
    getParams() {
      const params = _.cloneDeep(this.queryForm);
      const rangeKeyArr = [
        { attr: 'deliverTime', start: 'deliverStartTime', end: 'deliverEndTime', type: 'time' },
        { attr: 'receivableTime', start: 'receivableStartTime', end: 'receivableEndTime', type: 'time' },
        { attr: 'month', monthEnd: true, start: 'monthStart', end: 'monthEnd', type: 'time' },
        { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' },
        { attr: 'incomeTime', monthEnd: true, start: 'incomeStartTime', end: 'incomeEndTime', type: 'time' }
      ];
      paramsRangeFormat(rangeKeyArr, params);
      params.perPage = this.pageSize;
      return params;
    },
    queryEmpty() {
      this.queryForm = {};
      this.$emit('freshData', {});
    },
    approvalHttp(item, status) {
      approvelIncomeItem({ id: item.id, status }).then(res => {
        if (res.code === 200) {
          this.$message.success('审批成功');
          const params = this.getParams();
          params.page = this.incomeListData.page;
          this.$emit('freshData', params);
        }
      });
    },
    approval(item, isRevoke) {
      const h = this.$createElement;
      const showMobilePage = this.showMobilePage;
      const handelOk = () => {
        MessageBox.close();
        this.approvalHttp(item, !isRevoke ? 1 : 0);
      };
      const rejectFun = () => {
        MessageBox.close();
        this.approvalHttp(item, 2);
      };
      const msg = !isRevoke ? '请选择审批意见' : '是否作废审批';
      MessageBox.confirm('', '', {
        message: h('p', null, [
          h('div', null, msg),
          h('div', { class: 'btns-container' }, [
            h('el-button', { on: { click: handelOk }, props: { type: 'primary', size: 'small' }}, !isRevoke ? '通过' : '确定'),
            !isRevoke ? h('el-button', { on: { click: rejectFun }, props: { type: 'danger', size: 'small', plain: true }}, '拒绝 ') : null,
            h('el-button', { on: { click: MessageBox.close }, props: { size: 'small' }, class: 'cancel-btn-style' }, '取消')
          ])
        ]),
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        showClose: false,
        showCancelButton: false,
        showConfirmButton: false,
        type: 'warning',
        lockScroll: false,
        customClass: `del-message del-message-cancel message-box-order ${showMobilePage ? ' mobile-message' : ''}`,
        iconClass: 'del-icon',
        center: true
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.mengli-income-item {
  margin-bottom: 32px;
}
.flex {
  display: flex;
}
.title-container {
  display:flex;
  align-items:center;
  margin-bottom:16px;
  &.is-mobile {
    display: block;
    .create-btn {
      margin-top: 12px;
    }
  }
}
.img {
  width: 16px;
  margin-right: 5px;
}
.btns-container {
  margin-top: 20px;
  &::v-deep {
    .el-button {
      font-size: 14px;
    }
  }
}
.filter-wrap {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .fields-count {
    margin-left: 0;
  }
}
</style>
